from django.shortcuts import render
from bddjango.django import APIResponse, BaseListView, api_decorator
from bddjango.adminclass import conv_date_field_str_format
from django.db import models as m
from django.db.models import functions as f
from . import models, serializers, utils


class Statistics(BaseListView):
    """
    流量分析

    127.0.0.1:8000/api/flow_statistics/Statistics/
    """
    queryset = models.Statistics.objects.all()
    list_serializer_class = serializer_class = serializers.ListStatistics       # 用serializer_class生成wiki
    retrieve_serializer_class = serializers.RetrieveStatistics
    filter_fields = ['count_date', 'mobile']
    order_type_ls = ['-access_date']
    distinct_field_ls = ['access_date']

    # def get(self, request, *args, **kwargs):
    #     access_date_start = self.request.query_params.get('access_date_start')
    #     access_date_end = self.request.query_params.get('access_date_end')
    #     access_date_start, access_date_end = conv_date_field_str_format(access_date_start), conv_date_field_str_format(
    #         access_date_end)
    #     qs = super().get_queryset()
    #     if access_date_start and access_date_end:
    #         qs = qs.filter(access_date__range=[access_date_start, access_date_end])
    #     # queryset = utils.get_statistics_result(qs=qs, order=False, distinct=False, get_serializer_data=False)
    #     ret = utils.get_statistics_result(qs=qs)
    #     status, msg = 200, 'ok'
    #     return APIResponse(ret, status, msg)

    def get_queryset(self):     # get_list_queryset
        """
        这里用annotate添加了一些本不存在于表中的注释字段.
        """
        qs = super().get_queryset()
        access_date_start = self.request.query_params.get('access_date_start')
        access_date_end = self.request.query_params.get('access_date_end')
        access_date_start, access_date_end = conv_date_field_str_format(access_date_start), conv_date_field_str_format(access_date_end)
        if access_date_start and access_date_end:
            qs = qs.filter(access_date__range=[access_date_start, access_date_end])
        queryset = utils.get_statistics_result(qs=qs, order=False, distinct=False, get_serializer_data=False)
        return queryset






